package wang.lcs.pay.wx;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import wang.lcs.pay.util.print.LogHttpResult;
import wang.lcs.pay.wx.dto.WeixinResponseModel;

@Controller
@RequestMapping("/wx")
public class WeixinNotifyController {

    private static final Logger log = LoggerFactory.getLogger(WeixinNotifyController.class);

    @Resource
    WXPay wxpay;

    @RequestMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody String notifyXml, HttpServletRequest request, HttpServletResponse resp) throws Exception {

        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyXml); // 转换成map

        WeixinResponseModel model = new WeixinResponseModel();
        if (log.isDebugEnabled()) {
            new LogHttpResult(log).print(request, resp);
        }
        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            // model
            model.setReturnCode("SUCCESS");
        } else {
            // 签名错误，如果数据里没有sign字段，也认为是签名错误
            log.error("签名 Error !");
            new LogHttpResult(log).print(request, resp);
            model.setReturnCode("FAIL");
            model.setReturnMsg("签名失败");
        }
        return WXPayUtil.mapToXml(model.getNewMap());
    }

}